<template>
  <el-dialog 
    title="参数配置预览" 
    :visible.sync="dialogVisible"
    width="900px"
    append-to-body
    class="preview-dialog"
  >
    <div class="preview-content">
      <!-- 预览模式切换 -->
      <div class="preview-mode">
        <el-radio-group v-model="previewMode" size="mini">
          <el-radio-button label="json">JSON格式</el-radio-button>
          <el-radio-button label="tree">树形结构</el-radio-button>
          <el-radio-button label="summary">配置摘要</el-radio-button>
        </el-radio-group>
        
        <div class="preview-actions">
          <el-button 
            type="text" 
            icon="el-icon-download" 
            size="mini"
            @click="exportConfig"
            class="export-btn"
          >
            导出配置
          </el-button>
          <el-button 
            v-if="previewMode === 'json'"
            type="text" 
            icon="el-icon-copy-document" 
            size="mini"
            @click="copyJson"
            :loading="copyLoading"
          >
            {{ copyLoading ? '复制中...' : '复制JSON' }}
          </el-button>
        </div>
      </div>

      <!-- JSON预览 -->
      <div v-if="previewMode === 'json'" class="json-preview">
        <div class="json-toolbar">
          <el-button 
            type="text" 
            icon="el-icon-zoom-in" 
            size="mini"
            @click="zoomIn"
            :disabled="fontSize >= 16"
          >
            放大
          </el-button>
          <el-button 
            type="text" 
            icon="el-icon-zoom-out" 
            size="mini"
            @click="zoomOut"
            :disabled="fontSize <= 10"
          >
            缩小
          </el-button>
        </div>
        <pre 
          class="json-content" 
          :style="{ fontSize: fontSize + 'px' }"
          ref="jsonContent"
        >{{ json }}</pre>
      </div>

      <!-- 树形结构预览 -->
      <div v-else-if="previewMode === 'tree'" class="tree-preview">
        <el-tree 
          :data="treeData"
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span class="node-label">
              <i :class="data.icon" class="node-icon"></i>
              {{ node.label }}
            </span>
            <span v-if="data.desc" class="node-desc">{{ data.desc }}</span>
          </span>
        </el-tree>
      </div>

      <!-- 配置摘要预览 -->
      <div v-else class="summary-preview">
        <div class="summary-stats">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-value">{{ summary.totalGroups }}</div>
                <div class="stat-label">参数组</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-value">{{ summary.totalParams }}</div>
                <div class="stat-label">总参数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-value">{{ summary.baseParams }}</div>
                <div class="stat-label">基础参数</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card">
                <div class="stat-value">{{ summary.calcParams }}</div>
                <div class="stat-label">计算参数</div>
              </div>
            </el-col>
          </el-row>
        </div>

        <div class="summary-details">
          <el-collapse v-model="activeCollapse">
            <el-collapse-item title="参数组详情" name="groups">
              <div 
                v-for="group in summary.groupDetails" 
                :key="group.groupId"
                class="group-detail"
              >
                <h4>{{ group.groupName }}</h4>
                <div class="group-info">
                  <span>类型：{{ group.type }}</span>
                  <span>参数数量：{{ group.paramCount }}</span>
                  <span v-if="group.childGroups">子组：{{ group.childGroups }}</span>
                </div>
              </div>
            </el-collapse-item>
            
            <el-collapse-item title="数据类型分布" name="dataTypes">
              <el-table :data="summary.dataTypeStats" size="mini" border>
                <el-table-column prop="type" label="数据类型" width="120"></el-table-column>
                <el-table-column prop="count" label="数量" width="80"></el-table-column>
                <el-table-column prop="percentage" label="占比" width="100">
                  <template #default="scope">
                    <el-progress 
                      :percentage="scope.row.percentage" 
                      :show-text="false"
                    ></el-progress>
                    {{ scope.row.percentage }}%
                  </template>
                </el-table-column>
              </el-table>
            </el-collapse-item>
            
            <el-collapse-item title="验证规则统计" name="validations">
              <el-table :data="summary.validationStats" size="mini" border>
                <el-table-column prop="type" label="验证类型" width="120"></el-table-column>
                <el-table-column prop="count" label="数量" width="80"></el-table-column>
              </el-table>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>
    </div>

    <div slot="footer">
      <el-button @click="dialogVisible = false">关闭</el-button>
      <el-button 
        v-if="previewMode === 'json'" 
        type="primary" 
        @click="copyJson" 
        :loading="copyLoading"
      >
        {{ copyLoading ? '复制中...' : '复制JSON' }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'PreviewDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    json: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      previewMode: 'json',
      fontSize: 12,
      activeCollapse: ['groups', 'dataTypes', 'validations'],
      copyLoading: false,
      summary: {
        totalGroups: 0,
        totalParams: 0,
        baseParams: 0,
        calcParams: 0,
        groupDetails: [],
        dataTypeStats: [],
        validationStats: []
      }
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(value) {
        this.$emit('update:visible', value);
      }
    },
    
    // 树形数据
    treeData() {
      try {
        const config = JSON.parse(this.json);
        return this.buildTreeData(config);
      } catch (e) {
        return [];
      }
    }
  },
  watch: {
    visible: {
      handler(newVal) {
        if (newVal) {
          this.analyzeConfig();
        }
      },
      immediate: true
    },
    
    previewMode(newVal) {
      if (newVal === 'summary') {
        this.analyzeConfig();
      }
    }
  },
  methods: {
    // 复制JSON
    async copyJson() {
      this.copyLoading = true;
      try {
        await this.copyToClipboard(this.json);
      } catch (error) {
        console.error('复制失败:', error);
        this.$message.error('复制失败，请手动复制');
      } finally {
        this.copyLoading = false;
      }
    },

    // 通用的复制到剪贴板方法
    copyToClipboard(text) {
      return new Promise((resolve, reject) => {
        // 方法1: 使用现代 Clipboard API（推荐）
        if (navigator.clipboard && navigator.clipboard.writeText) {
          navigator.clipboard.writeText(text).then(() => {
            this.$message.success('JSON已复制到剪贴板');
            resolve();
          }).catch(err => {
            console.warn('Clipboard API 复制失败，使用备用方法:', err);
            this.fallbackCopyToClipboard(text).then(resolve).catch(reject);
          });
        } else {
          // 方法2: 使用传统的 execCommand 方法
          this.fallbackCopyToClipboard(text).then(resolve).catch(reject);
        }
      });
    },

    // 备用复制方法
    fallbackCopyToClipboard(text) {
      return new Promise((resolve, reject) => {
        try {
          // 创建临时文本区域
          const textArea = document.createElement('textarea');
          textArea.value = text;
          
          // 设置样式避免闪烁
          textArea.style.position = 'fixed';
          textArea.style.left = '-999999px';
          textArea.style.top = '-999999px';
          textArea.style.opacity = '0';
          textArea.style.pointerEvents = 'none';
          
          document.body.appendChild(textArea);
          
          // 选择和复制
          textArea.focus();
          textArea.select();
          
          // 尝试使用 execCommand
          let successful = false;
          try {
            successful = document.execCommand('copy');
          } catch (err) {
            console.warn('execCommand 失败:', err);
          }
          
          document.body.removeChild(textArea);
          
          if (successful) {
            this.$message.success('JSON已复制到剪贴板');
            resolve();
          } else {
            // 如果 execCommand 也失败，让用户手动复制
            this.showCopyManualDialog(text).then(resolve).catch(reject);
          }
        } catch (err) {
          reject(err);
        }
      });
    },

    // 如果自动复制失败，显示手动复制对话框
    showCopyManualDialog(text) {
      return new Promise((resolve, reject) => {
        this.$msgbox({
          title: '手动复制',
          message: `
            <div>
              <p style="margin-bottom: 10px; color: #f56c6c;">自动复制失败，请手动复制以下内容：</p>
              <textarea 
                id="manualCopyTextarea"
                style="width:100%; height:200px; font-family: monospace; font-size:12px; border:1px solid #ddd; padding:8px; border-radius:4px; resize: none;" 
                readonly
              >${text}</textarea>
              <p style="margin-top: 10px; font-size: 12px; color: #909399;">
                提示：按 Ctrl+A (Windows) 或 Cmd+A (Mac) 全选，然后按 Ctrl+C / Cmd+C 复制
              </p>
            </div>
          `,
          dangerouslyUseHTMLString: true,
          showCancelButton: false,
          confirmButtonText: '我已复制',
          customClass: 'manual-copy-dialog',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              this.$message.success('操作完成');
              resolve();
            } else {
              reject(new Error('用户取消复制'));
            }
            done();
          }
        }).then(() => {
          // 确认按钮点击
        }).catch(() => {
          reject(new Error('用户取消复制'));
        });

        // 自动选择文本区域内容
        this.$nextTick(() => {
          const textarea = document.getElementById('manualCopyTextarea');
          if (textarea) {
            textarea.focus();
            textarea.select();
          }
        });
      });
    },
    
    // 放大字体
    zoomIn() {
      if (this.fontSize < 16) {
        this.fontSize += 1;
      }
    },
    
    // 缩小字体
    zoomOut() {
      if (this.fontSize > 10) {
        this.fontSize -= 1;
      }
    },
    
    // 导出配置
    exportConfig() {
      try {
        const blob = new Blob([this.json], { 
          type: 'application/json;charset=utf-8' 
        });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `detection-config-${new Date().getTime()}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        this.$message.success('配置文件导出成功');
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('配置文件导出失败');
      }
    },
    
    // 分析配置
    analyzeConfig() {
      try {
        const config = JSON.parse(this.json);
        this.calculateSummary(config);
      } catch (e) {
        console.error('配置分析失败:', e);
      }
    },
    
    // 计算配置摘要
    calculateSummary(config) {
      if (!config) return;
      
      // 重置统计
      this.summary = {
        totalGroups: config.paramGroups?.length || 0,
        totalParams: 0,
        baseParams: 0,
        calcParams: 0,
        groupDetails: [],
        dataTypeStats: [],
        validationStats: []
      };
      
      const dataTypeCount = {};
      const validationCount = {
        required: 0,
        range: 0,
        regex: 0
      };
      
      // 遍历参数组
      config.paramGroups?.forEach((group) => {
        const groupDetail = {
          groupId: group.groupId,
          groupName: group.groupName,
          type: group.isNested ? '嵌套组' : (group.allowDynamicRows ? '动态表格' : '普通组'),
          paramCount: 0,
          childGroups: 0
        };
        
        if (group.isNested) {
          // 嵌套组
          group.childGroups?.forEach(childGroup => {
            groupDetail.childGroups++;
            childGroup.paramItems?.forEach(param => {
              this.processParam(param, dataTypeCount, validationCount);
              groupDetail.paramCount++;
            });
          });
        } else {
          // 普通组
          group.paramItems?.forEach(param => {
            this.processParam(param, dataTypeCount, validationCount);
            groupDetail.paramCount++;
          });
        }
        
        this.summary.groupDetails.push(groupDetail);
      });
      
      // 计算数据类型统计
      this.summary.dataTypeStats = Object.entries(dataTypeCount).map(([type, count]) => ({
        type: this.getDataTypeLabel(type),
        count,
        percentage: Math.round((count / this.summary.totalParams) * 100)
      }));
      
      // 计算验证规则统计 - 修复ESLint警告
      this.summary.validationStats = Object.entries(validationCount)
        .filter(([, count]) => count > 0)  // 使用逗号跳过第一个参数
        .map(([type, count]) => ({
          type: this.getValidationTypeLabel(type),
          count
        }));
    },
    
    // 处理参数统计
    processParam(param, dataTypeCount, validationCount) {
      this.summary.totalParams++;
      
      // 参数类型统计
      if (param.paramType === 'base') {
        this.summary.baseParams++;
      } else if (param.paramType === 'calculation') {
        this.summary.calcParams++;
      }
      
      // 数据类型统计
      const dataType = param.dataType || 'text';
      dataTypeCount[dataType] = (dataTypeCount[dataType] || 0) + 1;
      
      // 验证规则统计
      if (param.validateRule) {
        if (param.validateRule.required) validationCount.required++;
        if (param.validateRule.min !== undefined || param.validateRule.max !== undefined) {
          validationCount.range++;
        }
        if (param.validateRule.regex) validationCount.regex++;
      }
    },
    
    // 获取数据类型标签
    getDataTypeLabel(type) {
      const labels = {
        text: '文本',
        number: '数字',
        date: '日期',
        select: '下拉选择',
        textarea: '多行文本',
        attachment: '附件',
        boolean: '布尔值'
      };
      return labels[type] || type;
    },
    
    // 获取验证类型标签
    getValidationTypeLabel(type) {
      const labels = {
        required: '必填验证',
        range: '范围验证',
        regex: '正则验证'
      };
      return labels[type] || type;
    },
    
    // 构建树形数据
    buildTreeData(config) {
      const tree = [];
      
      // 基础信息
      tree.push({
        id: 'base',
        label: '基础信息',
        icon: 'el-icon-document',
        children: [
          { id: 'projectName', label: `项目名称: ${config.projectName}` },
          { id: 'projectId', label: `项目编码: ${config.projectId}` },
          { id: 'standardCode', label: `执行标准: ${config.standardCode}` },
          { id: 'description', label: `项目描述: ${config.description || '无'}` }
        ]
      });
      
      // 参数组
      const groupsNode = {
        id: 'groups',
        label: `参数组 (${config.paramGroups?.length || 0})`,
        icon: 'el-icon-folder-opened',
        children: []
      };
      
      config.paramGroups?.forEach((group, groupIndex) => {
        const groupNode = {
          id: `group-${groupIndex}`,
          label: group.groupName,
          icon: group.isNested ? 'el-icon-folder' : 'el-icon-tickets',
          children: []
        };
        
        if (group.isNested) {
          // 嵌套组
          group.childGroups?.forEach((childGroup, childIndex) => {
            const childNode = {
              id: `child-${groupIndex}-${childIndex}`,
              label: childGroup.groupName,
              icon: 'el-icon-document',
              children: this.buildParamNodes(childGroup.paramItems, `child-${groupIndex}-${childIndex}`)
            };
            groupNode.children.push(childNode);
          });
        } else {
          // 普通组
          groupNode.children = this.buildParamNodes(group.paramItems, `group-${groupIndex}`);
        }
        
        groupsNode.children.push(groupNode);
      });
      
      tree.push(groupsNode);
      return tree;
    },
    
    // 构建参数节点
    buildParamNodes(params, parentId) {
      if (!params) return [];
      
      return params.map((param, index) => ({
        id: `${parentId}-param-${index}`,
        label: param.paramName,
        icon: this.getParamIcon(param),
        desc: `${param.paramCode} | ${this.getDataTypeLabel(param.dataType)} | ${param.paramType === 'calculation' ? '计算参数' : '基础参数'}`
      }));
    },
    
    // 获取参数图标
    getParamIcon(param) {
      const icons = {
        text: 'el-icon-edit',
        number: 'el-icon-c-scale-to-original',
        date: 'el-icon-date',
        select: 'el-icon-thumb',
        textarea: 'el-icon-document-copy',
        attachment: 'el-icon-paperclip',
        boolean: 'el-icon-check'
      };
      return icons[param.dataType] || 'el-icon-question';
    }
  }
};
</script>

<style scoped>
.preview-dialog {
  max-height: 90vh;
}

.preview-content {
  height: 60vh;
  display: flex;
  flex-direction: column;
}

.preview-mode {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.preview-actions {
  display: flex;
  gap: 10px;
}

.export-btn {
  color: #409eff;
}

/* JSON预览样式 */
.json-preview {
  flex: 1;
  display: flex;
  flex-direction: column;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.json-toolbar {
  padding: 8px 12px;
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  gap: 10px;
}

.json-content {
  flex: 1;
  margin: 0;
  padding: 15px;
  background: #fafafa;
  overflow: auto;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  line-height: 1.4;
  color: #333;
}

/* 树形预览样式 */
.tree-preview {
  flex: 1;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  overflow: auto;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 13px;
  padding-right: 8px;
}

.node-icon {
  margin-right: 6px;
  color: #409eff;
}

.node-desc {
  font-size: 11px;
  color: #909399;
  margin-left: 10px;
}

/* 摘要预览样式 */
.summary-preview {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.summary-stats {
  margin-bottom: 10px;
}

.stat-card {
  text-align: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #606266;
}

.summary-details {
  flex: 1;
  overflow: auto;
}

.group-detail {
  margin-bottom: 12px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 4px;
}

.group-detail h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #303133;
}

.group-info {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #606266;
}

/* 手动复制对话框样式 */
:deep(.manual-copy-dialog) {
  min-width: 500px;
}

:deep(.manual-copy-dialog .el-message-box__message) {
  padding: 0;
}

:deep(.manual-copy-dialog .el-message-box__btns) {
  margin-top: 15px;
}
</style>